const express = require('express');
const router = express.Router();
const db = require('../config/database');

// 获取网站信息
router.get('/', async (req, res) => {
  try {
    const { populate } = req.query;
    
    const query = `
      SELECT 
        ws.id,
        ws.site_name,
        ws.site_description,
        ws.site_keywords,
        ws.logo_url,
        ws.favicon_url,
        ws.contact_email,
        ws.contact_phone,
        ws.address,
        ws.copyright,
        ws.icp_number,
        ws.analytics_code,
        ws.created_at,
        ws.updated_at
      FROM web_site ws
      ORDER BY ws.created_at DESC
      LIMIT 1
    `;
    
    const [rows] = await db.execute(query);
    
    if (rows.length === 0) {
      // 返回默认网站信息
      const defaultData = {
        id: 1,
        attributes: {
          site_name: 'YX Design',
          site_description: '专业的在线设计平台',
          site_keywords: '设计,在线设计,图片编辑',
          logo_url: null,
          favicon_url: null,
          contact_email: 'contact@yxdesign.com',
          contact_phone: null,
          address: null,
          copyright: '© 2024 YX Design. All rights reserved.',
          icp_number: null,
          analytics_code: null,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        }
      };
      
      return res.json({ data: defaultData });
    }
    
    const row = rows[0];
    const data = {
      id: row.id,
      attributes: {
        site_name: row.site_name,
        site_description: row.site_description,
        site_keywords: row.site_keywords,
        logo_url: row.logo_url,
        favicon_url: row.favicon_url,
        contact_email: row.contact_email,
        contact_phone: row.contact_phone,
        address: row.address,
        copyright: row.copyright,
        icp_number: row.icp_number,
        analytics_code: row.analytics_code,
        createdAt: row.created_at,
        updatedAt: row.updated_at
      }
    };
    
    res.json({ data });
  } catch (error) {
    console.error('获取网站信息失败:', error);
    res.status(500).json({ error: '获取网站信息失败' });
  }
});

module.exports = router;